/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Discribe：实现UI的鼠标拖拽移动 
* CreateTime：2020-05-26 10:01:56
* Version：1.0
* Modify Recoder：
*************************************************/

using TinyToolKit.UI;
using UnityEngine;
using UnityEngine.EventSystems;

namespace TinyToolKit
{
    public class DragUIBase : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
    {
        public RectTransform canvas; 
    
        protected RectTransform rectTransform;
        protected Vector2 offset; //存储开始拖拽时，鼠标和UI中心点的差值

        public void Start()
        {
            rectTransform = GetComponent<RectTransform>();

            if (canvas == null)
                canvas = TinyTool.Instance.GetManager<TUIManager>().CanvasRoot;
        }
        
        public virtual void OnBeginDrag(PointerEventData eventData)
        {
            if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, eventData.position,
                eventData.enterEventCamera, out var pos))
            {
                offset = rectTransform.anchoredPosition - pos;
            }
        }

        public virtual void OnDrag(PointerEventData eventData)
        {
            if (eventData.position.x < 0 || eventData.position.x > Screen.width || eventData.position.y < 0 ||
                eventData.position.y > Screen.height) return;
            
            if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, eventData.position,
                eventData.enterEventCamera, out var pos))
            {
                rectTransform.anchoredPosition = pos + offset; 
            }
        }

        public virtual void OnEndDrag(PointerEventData eventData)
        {
            offset = Vector2.zero;
        }
    } 
}
